package server.socket.server;

import server.socket.bean.EServer;
import server.socket.bean.ESocket;
import server.socket.bean.Message;
import server.socket.db.ChatModel;
import server.socket.handler.chat.ChatClientHandler;
import server.socket.handler.chat.ChatInfoHandler;
import server.util.InfoUtils.Info;
import server.util.MyUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ChatServer extends EServer {
    private Map<Integer, ChatClientHandler> clientMap = new HashMap<>();
    //单例模式
    private static ChatServer chatServer;

    public static ChatServer getChatServer() {
        return chatServer;
    }

    public ChatServer(int port) throws IOException {
        super(port);
        chatServer = this;
    }

    @Override
    public void update() {
        while (true) {
            try {
                ESocket client = new ESocket(serverSocket.accept());
                System.out.println("连接成功");
                ChatClientHandler handler = new ChatClientHandler(this, client, new ChatInfoHandler());
                handler.start();
                clients.add(handler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendToClient(int userId, Message message) {
        if (clientMap.containsKey(userId)) {
            ChatClientHandler chatClientHandler = clientMap.get(userId);
            if (chatClientHandler == null) return;
            chatClientHandler.sendInfo2Client(message);
        } else {  //离线的情况
            //将离线消息添加到数据库
            ChatModel.addMessage2DB(userId, MyUtils.toJson(message, 2));
        }
    }

    public void sendToClient(int userId, Info info) {
        if (clientMap.containsKey(userId)) {
            ChatClientHandler chatClientHandler = clientMap.get(userId);
            if (chatClientHandler == null) return;
            chatClientHandler.sendInfo2Client(info);
        }
    }

    public void sendMessage(Message message) {
//        if (message.getType() == 1) {   //单人对单人聊天
        sendToClient(message.getSender(), message);
        sendToClient(message.getReceiver(), message);
//        }
//        else {    //群聊
//
//        }
    }

    public void register(int userId, ChatClientHandler handler) {
        logout(userId);//确保先注销
        clientMap.put(userId, handler);
    }

    public void logout(int userId) {
        clientMap.remove(userId);
    }
}
